package com.beeantec.jnrerc.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

@Component
public class RestTamplateLogInterceptor implements ClientHttpRequestInterceptor {

    protected Logger log = LoggerFactory.getLogger(getClass());

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        Long startTime = System.nanoTime();
        ClientHttpResponse response = null;
        try {
            response = execution.execute(request, body);
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            return response;
        } finally {
            resp(request, response, startTime, body);
        }
    }

    public void resp(HttpRequest request, ClientHttpResponse response, long startTime, byte[] body) {
        try {
            log.info("-------------------------------------------------------------------");
            log.info("Req URI          : {}", request.getURI());
            log.info("Req Method       : {}", request.getMethod());
            log.info("Req Headers      : {}", request.getHeaders());
            log.info("Req Body		   : {}", new String((body == null || body.length == 0)
                    ? "".getBytes(StandardCharsets.UTF_8) : body));
            log.info("Resp Status code : {}", response.getStatusCode());
            log.info("Resp Status text : {}", response.getStatusText());
            log.info("Resp Headers     : {}", response.getHeaders());
            log.info("Resp Body        : {}", StreamUtils.copyToString(response.getBody(), Charset.defaultCharset()));
            log.info("Time			   : {} ms]", (System.nanoTime() - startTime) / 1000000);
            log.info("-------------------------------------------------------------------");
        } catch (Exception e) {
            log.error("resp error:{} ", e);
        }
    }
}
